package cn.wanda.bi.sunshine.platform.server.service;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import cn.wanda.bi.sunshine.platform.server.bean.mapper.AuthMappingMapper;
import cn.wanda.bi.sunshine.platform.server.bean.model.AuthMapping;
import cn.wanda.bi.sunshine.platform.server.bean.model.AuthMappingExample;
import cn.wanda.bi.sunshine.platform.server.controller.response.common.SimpleResponse;

/**
 * Created by wangfupeng1
 */
@Service
public class AuthMappingService {

	public static final Logger logger = LoggerFactory.getLogger(AuthMappingService.class);

	@Autowired
	private AuthMappingMapper authMappingMapper;

	public SimpleResponse<AuthMapping> create(AuthMapping authMapping) {
		authMappingMapper.insert(authMapping);
		return SimpleResponse.success(authMapping);
	}

	@Cacheable(value = "cache:authmapping", key = "'cache:authmapping:appid:'+#appid")
	public SimpleResponse<AuthMapping> get(String appid) {
		AuthMappingExample authMappingExample = new AuthMappingExample();
		authMappingExample.createCriteria().andAppidEqualTo(appid);
		List<AuthMapping> authMappings = authMappingMapper.selectByExample(authMappingExample);
		if (CollectionUtils.isEmpty(authMappings))
			return SimpleResponse.success();
		return SimpleResponse.success(authMappings.get(0));
	}

	@CacheEvict(value = "cache:authMapping", key = "'cache:authMapping:'+#authMapping.getAppid()")
	public SimpleResponse<AuthMapping> update(AuthMapping authMapping) {
		authMappingMapper.updateByPrimaryKeySelective(authMapping);
		return SimpleResponse.success(authMapping);
	}

	@CacheEvict(value = "cache:authMapping", key = "'cache:authMapping:'+#appid")
	public SimpleResponse<AuthMapping> delete(String appid) {
		AuthMappingExample authMappingExample = new AuthMappingExample();
		authMappingExample.createCriteria().andAppidEqualTo(appid);
		authMappingMapper.deleteByExample(authMappingExample);
		return SimpleResponse.success();
	}

	public SimpleResponse<List<AuthMapping>> list(Integer index, Integer limit, String description) {
		AuthMappingExample authMappingExample = new AuthMappingExample();
		if(StringUtils.isNotEmpty(description))
			authMappingExample.createCriteria().andDescriptionLike("%"+description+"%");
		authMappingExample.setOffset(index*limit-limit);
		authMappingExample.setLimit(limit);
		authMappingExample.setOrderByClause("id desc");
		List<AuthMapping> authMappings = authMappingMapper.selectByExample(authMappingExample);
		return SimpleResponse.success(authMappings);
	}

}
